using UnityEngine;
using QFramework;
using System.Linq;

namespace ProjectSurviver
{
	public partial class SimpleSword : ViewController
	{
		public float mCurrentSceneds = 0;

        void Update()
        {
            mCurrentSceneds += Time.deltaTime;

			if(mCurrentSceneds >= Global.SimpleAbilityDuretion.Value)
			{
				mCurrentSceneds = 0;

				var countTimes = Global.SuperSword.Value ? 2 : 1;
				var damageTimes = Global.SuperSword.Value ? Random.Range(2, 3 + 1) : 1;
				var distanceTimes = Global.SuperSword.Value ? 2 : 1;
				var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

				// OrderBy 从小到大排序
				// .Take(Global.SimpleSwordCount.Value) 获取数量
				foreach (var enemy in enemies
				.OrderBy(e => e.Direction2DFrom(Player.Default).magnitude)
				.Where(e => e.Direction2DFrom(Player.Default).magnitude < Global.SimpleSwordRange.Value * distanceTimes)
				.Take((Global.SimpleSwordCount.Value + Global.AdditionFlyThingCount.Value)* countTimes))
				{
					Sword.Instantiate()
					.Position(enemy.Position() + Vector3.left * 0.25f)
					.Show()
					.Self(self =>
					{
						var selfCache = self;
						self.OnTriggerEnter2DEvent(collider2D =>
						{
							var hurtBox = collider2D.GetComponent<HurtBox>();
							if(hurtBox)
							{
								if(hurtBox.Owner.CompareTag("Enemy"))
								{
									//enemy.Hurt(Global.SimpleAbilityDamage.Value);
									DamageSystem.CalculateDamage(Global.SimpleAbilityDamage.Value * damageTimes, hurtBox.Owner.GetComponent<Enemy>());
								}
							}
						}).UnRegisterWhenGameObjectDestroyed(gameObject);

						// 劈砍动画
						ActionKit
						.Sequence()
						.Callback(() =>
						{
							selfCache.enabled = false;
						})
						.Parallel(p =>
						{
							p.Lerp(0, 10, 0.2f, (z) =>
							{
								self.LocalEulerAnglesZ(z);
							});

							p.Append(ActionKit.Sequence().
							Lerp(0, 1.25f, 0.1f, scale =>selfCache.LocalScale(scale))
							.Lerp(1.25f, 1, 0.1f, scale =>selfCache.LocalScale(scale))
							);
						})
						.Callback(() => {selfCache.enabled = true;})
						.Parallel(p =>
						{
							p.Lerp(10, -180, 0.2f, z => selfCache.transform.LocalPositionZ(z));
							p.Append(ActionKit.Sequence()
							.Lerp(1, 1.25f, 0.1f, scale =>
							{
								selfCache.LocalScale(scale);
							})
							.Lerp(1.25f, 1, 0.1f, scale =>
							{
								selfCache.LocalScale(scale);
							}));
						})
						.Callback(() =>
						{
							selfCache.enabled = false;
						})
						.Lerp(-180, 0, 0.3f,z =>
						{
							selfCache.LocalEulerAnglesZ(z)
							.LocalScaleZ(z.Abs() / 180);
						})
						.Start(this, () =>
						{
							selfCache.DestroyGameObjGracefully();
						});
					});
				}
			}
        }
    }
}
